package conexaosimples;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.ResultSet;

public class TestaInsercao {
	public static void main(String[] args) throws SQLException { 
		
		try( Connection connection = Database.getConnection() ){
			 connection.setAutoCommit(false);
			 String sql = "INSERT INTO A_CATEGORIA$ (NOME, DESCRICAO) VALUES(?, ?)";

			 try(PreparedStatement statement = connection.prepareStatement( sql, new String[] {"CATEGORIAID"})  ){            
								
				adiciona("ELETRONICOS", "Eletronicos", statement);
				adiciona("ELETRODOMESTICOS"     , "Eletrodomesticos"    , statement);
				adiciona("MOVEIS"    , "Moveis"     , statement);
	
				connection.commit();
					
	         }catch (Exception e){
	        	e.printStackTrace();
	        	connection.rollback();
	        	System.out.println("rollback efetuado!!!");
	         }
		}
	}

	private static void adiciona(String nome, String descricao, PreparedStatement statement) throws SQLException {
//		if (nome.equals("Blueray")){
//			throw new IllegalArgumentException("Problema Ocorrido");
//		}	
		statement.setString(1, nome);
		statement.setString(2, descricao);
			
		boolean resultado = statement.execute();
		System.out.println(resultado);
		
		ResultSet  resultSet  = statement.getGeneratedKeys();

		while ( resultSet.next() ) {
		   long id = resultSet.getLong(1);
		   System.out.println( "ID: "+ id ); 
		}  

		resultSet.close();
	}	
	
}
